//
//  VerifyCell.m
//  Hxcsfw
//
//  Created by qiysoft on 2017/11/7.
//  Copyright © 2017年 企友软mac. All rights reserved.
//

#import "VerifyCell.h"

@implementation VerifyCell

- (void)awakeFromNib {
    [super awakeFromNib];

    self.PhoneTF.text = [WShareUtil getDataWithUserDefaultsForKey:@"USERNAME"];
    // Initialization code
    self.BView.layer.masksToBounds = YES;
    self.BView.layer.cornerRadius = 5;
    self.BView.layer.borderWidth = 1;
    self.BView.layer.borderColor = [[UIColor lightGrayColor] CGColor];
    
    self.BView2.layer.masksToBounds = YES;
    self.BView2.layer.cornerRadius = 5;
    self.BView2.layer.borderWidth = 1;
    self.BView2.layer.borderColor = [[UIColor lightGrayColor] CGColor];
    
    self.BView3.layer.masksToBounds = YES;
    self.BView3.layer.cornerRadius = 5;
    self.BView3.layer.borderWidth = 1;
    self.BView3.layer.borderColor = [[UIColor lightGrayColor] CGColor];
    
    self.LogBtn.layer.masksToBounds = YES;
    self.LogBtn.layer.cornerRadius = 5;

    //倒计时5分钟后的时间戳（从点击发送验证码按钮开始计时）
    NSInteger futureTime = [[[NSUserDefaults standardUserDefaults] objectForKey:@"futureTime"] integerValue];
    //已经触发过发送验证码按钮了
    if (futureTime > 0) {//验证码未失效不用再次发送，此时发送验证码按钮的交互性为NO
        [self changeButtonTitle];
    }
}

- (void)setSelected:(BOOL)selected animated:(BOOL)animated {
    [super setSelected:selected animated:animated];
}

- (IBAction)HqYzm:(id)sender {//获取验证码按钮
    
    if(![self panduanShouji] ) {
        return;
    }
    [self requestVerifyCode:self.PhoneTF.text];
}

- (IBAction)LogBtn:(id)sender {//验证码登录按钮
    
    self.LogBtn.enabled = NO;//登录禁点
    if(![self panduanShouji] ) {
        return;
    }
    if(![self checkInput] ) {
        return;
    }
    [self requestLogin:self.PhoneTF.text code:self.YzmTF.text];
}

- (IBAction)registerBtn:(id)sender {//注册
    [[NSNotificationCenter defaultCenter] postNotificationName:@"VERIFYREGISTER" object:nil];

}

#pragma mark - 获取验证码功能
- (void)requestVerifyCode:(NSString *)phone {

    NSDictionary *parametersDict = @{@"mode":@"native",@"service":@"shortlogin",@"content":@{@"revert":@"getcode",@"phone":phone}};

    NSString *secret = [NSString stringWithFormat:@"%@",[WHttpTool convertToJsonData:parametersDict]];
    NSDictionary *paramsDic = @{@"params":[CommonFunc encryptWithText:secret]};


    [WHttpTool POST:[WShareUtil getServerURL:nil] parameters:@{@"params":[CommonFunc encryptWithText:secret]} success:^(id responseObject) {
        WLog(@"------%@",responseObject);
        NSString *responseStr = [[NSString alloc] initWithData:responseObject encoding:NSUTF8StringEncoding];
        NSDictionary *JsonDic = [WHttpTool dictionaryWithJsonString:responseStr];
        NSString *messageStr = [JsonDic objectForKey:@"message"];
        NSString *successStr = [JsonDic objectForKey:@"success"];
        // 解密请求回的数据（字典）
        NSString *returnStr = [CommonFunc decryptWithText:messageStr];

        // json字符串转字典
        NSDictionary *returnDic = [WHttpTool dictionaryWithJsonString:returnStr];

        if ([returnDic[@"status"] isEqualToString:@"发送成功！"]) {
            //召唤主线程改变UI
            [self performSelectorOnMainThread:@selector(fsyzmcg) withObject:nil waitUntilDone:YES];
        }else{
            [SVProgressHUD showImage:nil status:@"发送失败！"];
            [SVProgressHUD setOffsetFromCenter:UIOffsetMake(0, WSCREENH_HEIGHT *0.5 - 70)];
            [SVProgressHUD dismissWithDelay:1.];
            [SVProgressHUD setBackgroundColor:[UIColor colorWithRed:0.9 green:0.91 blue:0.93 alpha:1]];
        }

    } failure:^(NSError *error) {
        [SVProgressHUD showImage:nil status:@"发送失败！"];
        [SVProgressHUD setOffsetFromCenter:UIOffsetMake(0, WSCREENH_HEIGHT *0.5 - 70)];
        [SVProgressHUD dismissWithDelay:1.];
        [SVProgressHUD setBackgroundColor:[UIColor colorWithRed:0.9 green:0.91 blue:0.93 alpha:1]];
    } showProgress:YES];
}

//登录请求
- (void)requestLogin:(NSString *)phone code:(NSString *)code{

    NSDictionary *parametersDict = @{@"mode":@"native",@"service":@"shortlogin",@"content":@{@"revert":@"login",@"phone":phone,@"code":code}};

    NSString *secret = [NSString stringWithFormat:@"%@",[WHttpTool convertToJsonData:parametersDict]];
    NSDictionary *paramsDic = @{@"params":[CommonFunc encryptWithText:secret]};


    [WHttpTool POST:[WShareUtil getServerURL:nil] parameters:@{@"params":[CommonFunc encryptWithText:secret]} success:^(id responseObject) {
        WLog(@"------%@",responseObject);
        NSString *responseStr = [[NSString alloc] initWithData:responseObject encoding:NSUTF8StringEncoding];
        NSDictionary *JsonDic = [WHttpTool dictionaryWithJsonString:responseStr];
        NSString *messageStr = [JsonDic objectForKey:@"message"];
        NSString *successStr = [JsonDic objectForKey:@"success"];
        // 解密请求回的数据（字典）
        NSString *returnStr = [CommonFunc decryptWithText:messageStr];

        // json字符串转字典
        NSDictionary *returnDic = [WHttpTool dictionaryWithJsonString:returnStr];

        if ([successStr boolValue]) {
//            if (self.delegate && [self.delegate respondsToSelector:@selector(btnOfVerifyLoginClicked)]) {
//                [self.delegate btnOfVerifyLoginClicked];
//            }
            [SVProgressHUD showImage:nil status:@"登录成功"];
            [SVProgressHUD setOffsetFromCenter:UIOffsetMake(0, WSCREENH_HEIGHT *0.5 - 70)];
            [SVProgressHUD dismissWithDelay:1.];
            [SVProgressHUD setBackgroundColor:[UIColor colorWithRed:0.9 green:0.91 blue:0.93 alpha:1]];   //背景颜色

            [WShareUtil sharedData].dicSession = returnDic;
            [[NSNotificationCenter defaultCenter] postNotificationName:@"LoginSuccess" object:nil];


            [WShareUtil saveDataWithUserDefaultsSetObject:phone ForKey:@"USERNAME"];
            [WShareUtil saveDataWithUserDefaultsSetObject:returnDic ForKey:@"DICSESSION"];

            // 登录成功直接进详情页的通知
            if ([[WShareUtil sharedData].Who isEqualToString:@"CSZX"]) {
                [[NSNotificationCenter defaultCenter] postNotificationName:@"CSZX" object:nil];
            }else if ([[WShareUtil sharedData].Who isEqualToString:@"WDWT"]) {
                [[NSNotificationCenter defaultCenter] postNotificationName:@"WDWT" object:nil];
            }else if ([[WShareUtil sharedData].Who isEqualToString:@"ZSFWPT"]) {
                [[NSNotificationCenter defaultCenter] postNotificationName:@"ZSFWPT" object:nil];
            }else if ([[WShareUtil sharedData].Who isEqualToString:@"SJPFW"]) {
                [[NSNotificationCenter defaultCenter] postNotificationName:@"SJPFW" object:nil];
            }else if ([[WShareUtil sharedData].Who isEqualToString:@"XHAZ"]) {
                [[NSNotificationCenter defaultCenter] postNotificationName:@"XHAZ" object:nil];
            }else if ([[WShareUtil sharedData].Who isEqualToString:@"WDXX"]) {
                [[NSNotificationCenter defaultCenter] postNotificationName:@"WDXX" object:nil];
            }else if ([[WShareUtil sharedData].Who isEqualToString:@"ZXYK"]) {
                [[NSNotificationCenter defaultCenter] postNotificationName:@"ZXYK" object:nil];
            }else if ([[WShareUtil sharedData].Who isEqualToString:@"FPMP"]) {
                [[NSNotificationCenter defaultCenter] postNotificationName:@"FPMP" object:nil];
            }else if ([[WShareUtil sharedData].Who isEqualToString:@"WDKC"]) {
                [[NSNotificationCenter defaultCenter] postNotificationName:@"WDKC" object:nil];
            }else if ([[WShareUtil sharedData].Who isEqualToString:@"WDDD"]) {
                [[NSNotificationCenter defaultCenter] postNotificationName:@"WDDD" object:nil];
            }else if ([[WShareUtil sharedData].Who isEqualToString:@"FWYY"]) {
                [[NSNotificationCenter defaultCenter] postNotificationName:@"FWYY" object:nil];
            }else if ([[WShareUtil sharedData].Who isEqualToString:@"SYSJPFW"]) {
                [[NSNotificationCenter defaultCenter] postNotificationName:@"SYSJPFW" object:nil];
            }else if ([[WShareUtil sharedData].Who isEqualToString:@"SYZXYK"]) {
                [[NSNotificationCenter defaultCenter] postNotificationName:@"SYZXYK" object:nil];
            }else if ([[WShareUtil sharedData].Who isEqualToString:@"SYWDXX"]) {
                [[NSNotificationCenter defaultCenter] postNotificationName:@"SYWDXX" object:nil];
            }else if ([[WShareUtil sharedData].Who isEqualToString:@"WBWDWT"]) {
                [[NSNotificationCenter defaultCenter] postNotificationName:@"WBWDWT" object:nil];
            }else if ([[WShareUtil sharedData].Who isEqualToString:@"KCGM"]){
                [[NSNotificationCenter defaultCenter] postNotificationName:@"KCGM" object:nil];
            }else if ([[WShareUtil sharedData].Who isEqualToString:@"HYJF"]){
                [[NSNotificationCenter defaultCenter] postNotificationName:@"HYJF" object:nil];
            }else if ([[WShareUtil sharedData].Who isEqualToString:@"SWBQX"]){
                [[NSNotificationCenter defaultCenter] postNotificationName:@"SWBQX" object:nil];
            }else if ([[WShareUtil sharedData].Who isEqualToString:@"ASWBQX"]){
                [[NSNotificationCenter defaultCenter] postNotificationName:@"ASWBQX" object:nil];
            }else if ([[WShareUtil sharedData].Who isEqualToString:@"HAWBQX"]){
                [[NSNotificationCenter defaultCenter] postNotificationName:@"HAWBQX" object:nil];
            }else if ([[WShareUtil sharedData].Who isEqualToString:@"AWBQX"]){
                [[NSNotificationCenter defaultCenter] postNotificationName:@"AWBQX" object:nil];
            }
            
        } else {
            [WShareUtil showAlert:@"温馨提示" message:@"短信验证码错误！请重新输入"];
        }
        self.LogBtn.enabled = YES;

    } failure:^(NSError *error) {
        [SVProgressHUD showImage:nil status:@"登录失败"];
        [SVProgressHUD setOffsetFromCenter:UIOffsetMake(0, WSCREENH_HEIGHT *0.5 - 70)];
        [SVProgressHUD dismissWithDelay:1.];
        [SVProgressHUD setBackgroundColor:[UIColor colorWithRed:0.9 green:0.91 blue:0.93 alpha:1]];
        self.LogBtn.enabled = YES;

    } showProgress:YES];
}

- (void)touchesBegan:(NSSet<UITouch *> *)touches withEvent:(UIEvent *)event {
    [self endEditing:YES];
}

//判断手机号
-(BOOL)panduanShouji {
    BOOL resultBool = NO;
    
    if (![self.PhoneTF.text isUserPhone]) {
        [WShareUtil showAlert:@"温馨提示" message:@"请输入正确的手机号！"];
        self.LogBtn.enabled = YES;
        return resultBool;
    }
    return YES;
}

//判断登录条件
#pragma mark - check input
-(BOOL)checkInput{
    BOOL resultBool = NO;
    NSString *userNameString = self.PhoneTF.text;
    if ([WShareUtil strNilOrEmpty:userNameString]) {
        [WShareUtil showAlert:@"温馨提示" message:@"手机号不能为空！"];
        self.LogBtn.enabled = YES;
        //        self.btnOfBack.enabled = YES;
        
        return resultBool;
    }
    
    userNameString = [userNameString stringByReplacingOccurrencesOfString:@" " withString:@""];
    if ([WShareUtil strNilOrEmpty:userNameString]) {
        [WShareUtil showAlert:@"温馨提示" message:@"手机号不能全部为空格！"];
        self.LogBtn.enabled = YES;
        //        self.btnOfBack.enabled = YES;
        
        return resultBool;
    }
    
    if ([WShareUtil strNilOrEmpty:self.YzmTF.text]) {
        [WShareUtil showAlert:@"温馨提示" message:@"短信验证码不能为空！"];
        self.LogBtn.enabled = YES;
        //        self.btnOfBack.enabled = YES;
        
        return resultBool;
    }
    
    NSString *strPassword = self.YzmTF.text;
    strPassword = [strPassword stringByReplacingOccurrencesOfString:@" " withString:@""];
    if ([WShareUtil strNilOrEmpty:strPassword]) {
        [WShareUtil showAlert:@"温馨提示" message:@"短信验证码不能全部为空格！"];
        self.LogBtn.enabled = YES;
        //        self.btnOfBack.enabled = YES;
        
        return resultBool;
    }
    
    if ([WShareUtil strNilOrEmpty:self.TPYzmTF.text]) {
        [WShareUtil showAlert:@"温馨提示" message:@"图片验证码不能为空！"];
        self.LogBtn.enabled = YES;
        //        self.btnOfBack.enabled = YES;
        
        return resultBool;
    }
    
    NSString *tpyzmtf = self.TPYzmTF.text;
    tpyzmtf = [tpyzmtf stringByReplacingOccurrencesOfString:@" " withString:@""];
    if ([WShareUtil strNilOrEmpty:tpyzmtf]) {
        [WShareUtil showAlert:@"温馨提示" message:@"图片验证码不能全部为空格！"];
        self.LogBtn.enabled = YES;
        //        self.btnOfBack.enabled = YES;
        
        return resultBool;
    }

    if (![[self.TPYzmTF.text lowercaseString] isEqualToString:[WShareUtil sharedData].SmallTpyzm]) {
        [WShareUtil showAlert:@"温馨提示" message:@"图片验证码错误！请重新输入"];
        self.LogBtn.enabled = YES;
        //        self.btnOfBack.enabled = YES;
        
        return resultBool;
    }
    
    return YES;
}

-(void)fsyzmcg {
    
    [WShareUtil ShowWaitView:NO];
    // -- 显示“发送成功”
    [SVProgressHUD showImage:nil status:@"发送成功"];
    [SVProgressHUD setOffsetFromCenter:UIOffsetMake(0, WSCREENH_HEIGHT *0.5 - 70)];
    [SVProgressHUD dismissWithDelay:1.];
    [SVProgressHUD setBackgroundColor:[UIColor colorWithRed:0.9 green:0.91 blue:0.93 alpha:1]];   //背景颜色
    
    // --验证码发送成功后再执行下边的代码--
    
    //当前的时间戳
    NSInteger timeInterval = (NSInteger)[[NSDate date] timeIntervalSince1970];
    //倒计时5分钟后的时间戳（从点击发送验证码按钮开始计时）
    NSInteger futureTime = (NSInteger)(timeInterval + 3*60);
    [[NSUserDefaults standardUserDefaults] setInteger:futureTime forKey:@"futureTime"];
    [[NSUserDefaults standardUserDefaults] synchronize];
    [self changeButtonTitle];
    
}

#pragma mark - 发送按钮的标题倒计时
- (void)changeButtonTitle
{
    NSDate *date = [NSDate date];
    NSInteger timeInterval = (NSInteger)[date timeIntervalSince1970];
    //5分钟后的时间
    NSInteger futureTime = [[[NSUserDefaults standardUserDefaults] objectForKey:@"futureTime"] integerValue];
    //时间差（5分钟后的时间与当前的时间差）
    NSInteger timeCha = futureTime - timeInterval;
    
    //倒计时默认时间
    __block NSInteger time = 300;
    
    if (futureTime > 0) {
        time = timeCha;
    }
    
    dispatch_queue_t queue = dispatch_get_global_queue(DISPATCH_QUEUE_PRIORITY_DEFAULT, 0);
    dispatch_source_t timer = dispatch_source_create(DISPATCH_SOURCE_TYPE_TIMER, 0, 0, queue);
    
    dispatch_source_set_timer(timer,dispatch_walltime(NULL, 0),1.0*NSEC_PER_SEC, 0); //每秒执行
    
    dispatch_source_set_event_handler(timer, ^{
        
        if(time <= 0){ //倒计时结束，关闭
            
            dispatch_source_cancel(timer);
            dispatch_async(dispatch_get_main_queue(), ^{
                self.HqYzm.userInteractionEnabled = YES;
                //移除上次的计时
                [[NSUserDefaults standardUserDefaults] removeObjectForKey:@"futureTime"];
                
                //设置按钮的样式
                [self.HqYzm setTitle:@"获取验证码" forState:UIControlStateNormal];
                [self.HqYzm setTitleColor:[UIColor whiteColor] forState:UIControlStateNormal];
                
            });
            
        }else{
            
            NSInteger seconds = time;
            dispatch_async(dispatch_get_main_queue(), ^{
                self.HqYzm.userInteractionEnabled = NO;
                //设置按钮显示读秒效果
                [self.HqYzm setTitle:[NSString stringWithFormat:@"%.2ld秒后重发", (long)seconds] forState:UIControlStateNormal];
                [self.HqYzm setTitleColor:[UIColor whiteColor] forState:UIControlStateNormal];
                
            });
            time--;
        }
    });
    dispatch_resume(timer);
}
#pragma mark - 262行设置倒计时时间

@end
